package com.system.connect.springboot_flowers.service.impl;

import com.system.connect.springboot_flowers.dto.AddressDTO;
import com.system.connect.springboot_flowers.entity.UserAddress;
import com.system.connect.springboot_flowers.mapper.UserAddressMapper;
import com.system.connect.springboot_flowers.service.IUserAddressService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 用户收货地址表 服务实现类
 * </p>
 *
 * @author yang
 * @since 2025-03-22
 */
@Service
public class UserAddressServiceImpl extends ServiceImpl<UserAddressMapper, UserAddress> implements IUserAddressService {
    @Autowired
    private UserAddressMapper addressMapper;

    @Override
    public List<UserAddress> getAddressList(Long userId) {
        return addressMapper.selectByUserId(userId);
    }

    @Override
    @Transactional
    public void addAddress(Long userId, AddressDTO addressDTO) {
        UserAddress address = new UserAddress();
        BeanUtils.copyProperties(addressDTO, address);
        address.setUserId(userId);

        // 如果是默认地址，先将其他地址设为非默认
        if (address.getIsDefault()) {
            addressMapper.clearDefaultAddress(userId);
        }

        addressMapper.insert(address);
    }

    @Override
    @Transactional
    public void updateAddress(Long userId, AddressDTO addressDTO) {
        UserAddress address = addressMapper.selectById(addressDTO.getId());
        if (address == null || !address.getUserId().equals(userId)) {
           // throw new BusinessException("地址不存在或无权限修改");
            System.out.println("地址不存在或无权限修改");
        }

        BeanUtils.copyProperties(addressDTO, address);

        // 如果是默认地址，先将其他地址设为非默认
        if (address.getIsDefault()) {
            addressMapper.clearDefaultAddress(userId);
        }

        addressMapper.updateById(address);
    }

    @Override
    public void deleteAddress(Long userId, Long addressId) {
        UserAddress address = addressMapper.selectById(addressId);
        if (address == null || !address.getUserId().equals(userId)) {
            // throw new BusinessException("地址不存在或无权限修改");
            System.out.println("地址不存在或无权限修改");
        }

        addressMapper.deleteById(addressId);
    }

    @Override
    @Transactional
    public void setDefaultAddress(Long userId, Long addressId) {
        UserAddress address = addressMapper.selectById(addressId);
        if (address == null || !address.getUserId().equals(userId)) {
            // throw new BusinessException("地址不存在或无权限修改");
            System.out.println("地址不存在或无权限修改");
        }

        // 先将所有地址设为非默认
        addressMapper.clearDefaultAddress(userId);

        // 将指定地址设为默认
        address.setIsDefault(true);
        addressMapper.updateById(address);
    }

}
